from sqlalchemy.orm import Session
import hashlib
from app.core.database import SessionLocal
from app.models.user import User


def _hash_password(password: str) -> str:
    """使用 SHA-256 对密码进行哈希。"""
    return hashlib.sha256(password.encode()).hexdigest()


def create_user(username: str, password: str) -> tuple[bool, str]:
    """注册用户。如果用户名已存在则返回失败信息。"""
    db: Session = SessionLocal()
    try:
        if db.query(User).filter(User.username == username).first():
            return False, "用户名已存在"
        user = User(username=username, password=_hash_password(password))
        db.add(user)
        db.commit()
        return True, "注册成功"
    except Exception as e:
        db.rollback()
        return False, f"注册失败: {e}"
    finally:
        db.close()


def verify_user(username: str, password: str) -> tuple[bool, str]:
    """验证用户名和密码是否正确。"""
    db: Session = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username).first()
        if not user:
            return False, "用户不存在"
        if user.password != _hash_password(password):
            return False, "密码错误"
        return True, "登录成功"
    finally:
        db.close()


def get_current_user_id(username: str) -> int:
    """根据用户名获取用户ID。"""
    db: Session = SessionLocal()
    try:
        user = db.query(User).filter(User.username == username).first()
        return user.id if user else None
    finally:
        db.close()